/**
 * Controll load-inroom-order-list.vm and load-logistics-plan-list.vm
 * Created by zzy on 2016/12/13.
 */
require('easyui');
require('layout/util');
require("libs/jquery.jqprint-0.3.js");
var $alert = require("libs/alert");
var $confirm = require("libs/confirm");
var loadInfoId='';
var fixedW = 3;
var fixedV = 6;
var isAddInroomOrder=false;
var orderStatus={"commit":"已提交","c_collect":"已揽收","c_receive":"已收货",
    "c_ourtoom":"集货出库","p_inroom":"转运入库","p_outroom":"转运出库","o_inroom":"海外入库"};
$(function () {
    $("#a_to_inroom").show();
    //物流计划列表初始化
    logisticsPlanGridInit();
    //入库单列表初始化
    inroomGridInit();
    //筛选入库单按钮点击事件
    $("#a_to_inroom").on("click",function () {
        var $panel = $("#logistics_plan_table").datagrid('getPanel');
        var $selectRadio = $panel.find('.radio:checked');
        if($selectRadio.length === 0){
            $alert("请选择物流计划!");
            return false;
        }
        window.location.href="load-inroom-order-list?logisticsPlanId="+$selectRadio.eq(0).val();
    });
    //生成配载单按钮点击事件
    $("#button_to_loadinfo").on("click",function () {
        var $selects = $("#inroom_order_table").datagrid("getSelections");
        if($selects.length==0){
            $alert("请选择入库单!");
            return false;
        }
        var arr = [];
        $.each($selects,function (index,obj) {
            var order = {};
            order["orderId"] = obj.orderId;
            arr.push(order);
        });
        var $btn = $("#button_to_loadinfo");
        $btn.button('loading');
        if($btn.text()=="生成配载单"){
            $.ajax({
                url:'api/v1/p/mms/loadInfo/create',
                type:'post',
                contentType: "application/json; charset=utf-8",
                data:JSON.stringify(arr),
                dataType:'json',
                success:function (result) {
                    if(result.code == 200){
                        loadInfoId = result.data.loadInfoId;
                        //读取配载单
                        loadInfoLoad(loadInfoId);
                    }else{
                        $alert(result.message);
                    }
                }
            })
        }else{
            if(loadInfoId==''){
                $alert("请先生成配载单!");
                return false;
            }else{
                var obj = {};
                obj["loadInfoId"]=loadInfoId;
                obj["orderIds"]=arr;
            }
            $.ajax({
                url:'api/v1/p/mms/loadInfo/inRoomOrderAdd',
                type:'post',
                contentType: "application/json; charset=utf-8",
                data:JSON.stringify(obj),
                dataType:'json',
                success:function (result) {
                    if(result.code == 200){
                        loadInfoId = result.data.loadInfoId;
                        //读取配载单
                        loadInfoLoad(loadInfoId);
                    }else{
                        $alert(result.message);
                    }
                }
            })
        }
    });
    //移除配载单中入库单
    $("#load_inroom_order_table").on("click",".remove",function () {
        var thisId = $(this).parent().parent().children().eq(0).text();
        removeLoadInroomOrder(1*thisId,$(this));
    });
    //继续向已生成配载单中添加入库单
    $("#button_add_inroom_order").on("click",function () {
        if(loadInfoId==''){
            $alert("请先生成配载单!")
            return false;
        }else{
            isAddInroomOrder = true;
            $("#dialog_loadinfo table tbody").append("<tr></tr>");
            $('#dialog_loadinfo').modal("hide");
        }
    });
    //点击关闭按钮时触发
    $('#dialog_loadinfo').on('hide.bs.modal', function () {
        if($("#dialog_loadinfo table tbody tr").length<=0){
            $alert("配载单内必须有一条入库单信息!");
            return false;
        }
    });
    $('#dialog_loadinfo').on('show.bs.modal', function () {
        $("#button_to_loadinfo").button('reset');
    });
    //打印按钮
    $('#button_print').on('click',function () {
        if($("#dialog_loadinfo table tbody tr").length<=0){
            $alert("配载单内必须有一条入库单信息!");
            return false;
        }else{
            $.ajax({
                url:'api/v1/p/mms/loadInfo/inRoomOrderList',
                type:'post',
                data:{
                    loadInfoId:1*loadInfoId,
                    page:1,
                    rows:100
                },
                dataType:'json',
                success:function (result) {
                    if(result.code == 200) {
                        var data = result.data.rows;
                        var $tbody = $("#load_inroom_order_table_print tbody");
                        $tbody.empty();
                        var rows='';
                        $.each(data,function (index,row) {
                            rows=rows+"<tr><td style='display: none;'>"+row.orderId+"</td><td>"+row.orderNo+
                                "</td><td>"+row.collectWarehouseName+"</td><td>"+row.toWarehouseName+"</td><td>"+
                                row.logisticsName+"</td><td>"+row.logisticsPlanName+"</td>";
                            if(row.cNums==''||row.cNums==null){
                                rows=rows+"<td>"+row.tNums+"</td>";
                            }else{
                                rows=rows+"<td>"+row.cNums+"</td>";
                            }
                            if(row.cWeight==''||row.cWeight==null){
                                rows=rows+"<td>"+Number(row.tWeight).toFixed(fixedW)+"</td>";
                            }else{
                                rows=rows+"<td>"+Number(row.cWeight).toFixed(fixedW)+"</td>";
                            }
                            if(row.cVolumn==''||row.cVolumn==null){
                                rows=rows+"<td>"+Number(row.tVolumn).toFixed(fixedV)+"</td>";
                            }else{
                                rows=rows+"<td>"+Number(row.cVolumn).toFixed(fixedV)+"</td>";
                            }
                            rows=rows+"<td>"+orderStatus[row.orderStatus]+"</td>";
                            rows=rows+"<td>"+row.outroomDt+"</td>";
                        });
                        $tbody.append(rows);
                        var printModule1 = $("#div_loadinfo_detail").html();
                        $("#div_loadinfo_detail_print").append(printModule1);
                        $("#print_page").show().jqprint();
                        $("#print_page").hide();
                        $("#div_loadinfo_detail_print").empty();
                        $tbody.empty();
                    }else{
                        $alert(result.message);
                    }
                }
            });
            /*var printModule1 = $("#div_loadinfo_detail").html();
            $("#div_loadinfo_detail_print").append(printModule1);
            var printModule2 = $("#load_inroom_order_table tbody").html();
            var rowCount = $(printModule2).find('tr').length;
            console.log(rowCount);
            return false;
            var a = $(printModule2).remove();
            $("#load_inroom_order_table_print tbody").append(printModule2);
            $("#print_page").show().jqprint();
            $("#print_page").hide();
            $("#div_loadinfo_detail_print").html('');*/
        }
    });
    //dialog关闭时清空数据
    $('#dialog_loadinfo').on('hidden.bs.modal', function () {
        $("#div_loadinfo_detail .form-group div").empty();
        $("#load_inroom_order_table tbody").empty();
        if(isAddInroomOrder){
            $("#button_to_loadinfo").text("添加到已生成的配载单中");
            isAddInroomOrder = false;
        }else{
            $("#button_to_loadinfo").text("生成配载单");
        }
        $("#inroom_order_table").datagrid("reload");
        //取消全选
        $("#inroom_order_table").datagrid("unselectAll");
    });
    $("body").on("change",".radio",function () {
        var $panel = $("#logistics_plan_table").datagrid('getPanel');
        $panel.find('.radio').attr('checked',false);
        this.checked = true;
    })
});
function loadInfoLoad(loadInfoId) {
    $.ajax({
        url:'api/v1/p/mms/loadInfo/load',
        type:'post',
        data:{
            loadInfoId:loadInfoId
        },
        dataType:'json',
        success:function (result) {
            if(result.code == 200){
                var $data = result.data;
                //重新对dialog填充数据
                dialogReload($data);
            }else{
                $alert(result.message);
            }
        }
    })
}
//重新对dialog填充数据
function dialogReload($data){
    $('#mLoadInfoTitle').text('配载单 '+$data.loadInfoNo);
    var $fillText = $('#div_loadinfo_detail').find('.fill-text');
    $fillText.empty();
    $fillText.eq(0).append("<span>"+$data.fromWarehouseName+"</span>");
    $fillText.eq(1).append("<span>"+$data.toWarehouseName+"</span>");
    $fillText.eq(2).append("<span>"+$data.logisticsName+"</span>");
    $fillText.eq(3).append("<span>"+$data.providerCode+"</span>");
    $fillText.eq(4).append("<span>"+$data.logisticsPlanName+"</span>");
    // if($data.logisticsType=='A'){
    //     $fillText.eq(5).append("<span>"+"空运"+"</span>");
    // }else{
    //     $fillText.eq(5).append("<span>"+"海运"+"</span>");
    // }
    $fillText.eq(5).append("<span>"+$data.serviceCategory+"</span>");
    $fillText.eq(6).append("<span>"+$data.startPort+"</span>");
    $fillText.eq(7).append("<span>"+$data.transferPort+"</span>");
    $fillText.eq(8).append("<span>"+$data.destPort+"</span>");
    $fillText.eq(9).append("<span>"+$data.estimateLeaveDt+"</span>");
    $fillText.eq(10).append("<span>"+$data.estimateArriveDt+"</span>");
    $fillText.eq(11).append("<span>"+$data.tBoxNums+"</span>");
    $fillText.eq(12).append("<span>"+Number($data.tWeight).toFixed(fixedW)+"</span>");
    $fillText.eq(13).append("<span>"+Number($data.tVolumn).toFixed(fixedV)+"</span>");
    if($data.state=='N'){
        $fillText.eq(14).append("<span>"+"新建"+"</span>");
    }else{
        $fillText.eq(14).append("<span>"+"已订舱"+"</span>");
    }
    $.ajax({
        url:'api/v1/p/mms/loadInfo/inRoomOrderList',
        type:'post',
        data:{
            loadInfoId:$data.loadInfoId,
            page:1,
            rows:100
        },
        dataType:'json',
        success:function (result) {
            if(result.code == 200) {
                var data = result.data.rows;
                var $tbody = $("#load_inroom_order_table tbody");
                $tbody.empty();
                var rows='';
                $.each(data,function (index,row) {
                    rows=rows+"<tr><td style='display: none;'>"+row.orderId+"</td><td>"+row.orderNo+
                        "</td><td>"+row.collectWarehouseName+"</td><td>"+row.toWarehouseName+"</td><td>"+
                        row.logisticsName+"</td><td>"+row.logisticsPlanName+"</td>";
                    if(row.cNums==''||row.cNums==null){
                        rows=rows+"<td>"+row.tNums+"</td>";
                    }else{
                        rows=rows+"<td>"+row.cNums+"</td>";
                    }
                    if(row.cWeight==''||row.cWeight==null){
                        rows=rows+"<td>"+Number(row.tWeight).toFixed(fixedW)+"</td>";
                    }else{
                        rows=rows+"<td>"+Number(row.cWeight).toFixed(fixedW)+"</td>";
                    }
                    if(row.cVolumn==''||row.cVolumn==null){
                        rows=rows+"<td>"+Number(row.tVolumn).toFixed(fixedV)+"</td>";
                    }else{
                        rows=rows+"<td>"+Number(row.cVolumn).toFixed(fixedV)+"</td>";
                    }
                    rows=rows+"<td>"+orderStatus[row.orderStatus]+"</td>";
                    rows=rows+"<td>"+row.outroomDt+"</td>";
                    rows=rows+"<td><a href='#' class='remove'>"+"移除"+"</a></td></tr>"
                });
                $tbody.append(rows);
                $('#dialog_loadinfo').modal("show");
            }else{
                $alert(result.message);
            }
        }
    });
}
function removeLoadInroomOrder(orderId,$this) {
    $.ajax({
        url:"api/v1/p/mms/loadInfo/inRoomOrderRemove",
        type:'post',
        data:{
            loadInfoId:1*loadInfoId,
            orderId:1*orderId
        },
        dataType:'json',
        success:function (result) {
            if(result.code == 200) {
                var _num = $this.parent().parent().children().eq(6).text();
                var _weight = $this.parent().parent().children().eq(7).text();
                var _volumn = $this.parent().parent().children().eq(8).text();
                var oldNum = $("#div_loadinfo_detail .form-group:eq(11) div span").text();
                var oldWeight = $("#div_loadinfo_detail .form-group:eq(12) div span").text();
                var oldVolumn = $("#div_loadinfo_detail .form-group:eq(13) div span").text();
                $("#div_loadinfo_detail .form-group:eq(11) div span").text(1*oldNum-_num);
                $("#div_loadinfo_detail .form-group:eq(12) div span").text(Number(1*oldWeight-_weight).toFixed(fixedW));
                $("#div_loadinfo_detail .form-group:eq(13) div span").text(Number(1*oldVolumn-_volumn).toFixed(fixedV));
                $this.parent().parent().remove();
            }else{
                $alert(result.message);
            }
        }
    })
}
function logisticsPlanGridInit(){
    $("#logistics_plan_table").datagrid({
        url:'api/v1/p/mms/loadInfo/logisticsPlanList',
        border : false,
        height:$(window).height(),
        pagination : true,
        idField : 'id',
        pageSize : 20,
        pageList : [ 20, 50,  100 ],
        emptyMsg : "暂无数据",
        singleSelect: true,
        rownumbers:true,
        columns:[[
            {
                field:'id',
                title:'',
                formatter:function (value,row,index) {
                    return "<input class='radio' type='radio' value='"+value+"'>";
                }
            },{
                field:'name',
                title:'计划名称',
                formatter:function (value,row,index) {
                    return "<a href='load-info-logistics-plan-detail?id="+row.id+"'>"+value+"</a>";
                }
            },{
                field:'logisticsName',
                title:'物流产品'
            },{
                field:'toWarehouseName',
                title:'海外仓'
            },{
                field:'startPort',
                title:'起运港'
            },{
                field:'destPort',
                title:'目的港'
            },{
                field:'estimateLeaveDt',
                title:'预计离港日期'
            },{
                field:'estimateArriveDt',
                title:'预计到达日期'
            },{
                field:'tLastOrderDt',
                title:'截单时间'
            },{
                field:'tLastCollectDt',
                title:'截货时间'
            },{
                field:'lastOrderDt',
                title:'下单最迟时间'
            },{
                field:'lastCollectDt',
                title:'企业送货最迟时间'
            }
        ]],
        loadFilter:function(data){
            if(data.code=='200'){
                return data.data;
            }
        },
        onClickRow:function (index,data) {
            var $selectRow = $("#logistics_plan_table").datagrid('getPanel').find('.datagrid-row-selected');
            $selectRow.find('.radio').trigger('change');
        }
    })
}
function inroomGridInit() {
    var href = window.location.href;
    var logisticsPlanId='';
    if(href.indexOf("logisticsPlanId")>=0){
        logisticsPlanId = $.getUrlParam('logisticsPlanId');
    }
    $("#inroom_order_table").datagrid({
        url:'api/v1/p/mms/loadInfo/inRoomOrderFilter',
        border : false,
        height:$(window).height(),
        pagination : true,
        idField : 'id',
        pageSize : 20,
        pageList : [ 20, 50,  100 ],
        emptyMsg : "暂无数据",
        checkOnSelect : true,//单击选中
        selectOnCheck : true,
        rownumbers:true,
        queryParams: {
            logisticsPlanId: 1*logisticsPlanId
        },
        frozenColumns:[[{
            field : 'orderId',
            checkbox:true
        },{
            field:'orderNo',
            title:'入库单号'
        }]],
        columns:[[
            {
                field:'collectWarehouseName',
                title:'国内仓'
            },{
                field:'toWarehouseName',
                title:'海外仓'
            },{
                field:'logisticsName',
                title:'物流产品'
            },{
                field:'logisticsPlanName',
                title:'物流计划'
            },{
                field:'cNums',
                title:'件数',
                formatter:function (value,row,index) {
                    if(value==''){
                        return row.tNums;
                    }else{
                        return value;
                    }
                }
            },{
                field:'cWeight',
                title:'毛重(Kg)',
                formatter:function (value,row,index) {
                    if(value==''){
                        return Number(row.tWeight).toFixed(fixedW);
                    }else{
                        return Number(value).toFixed(fixedW);
                    }
                }
            },{
                field:'cVolumn',
                title:'体积(CBM)',
                formatter:function (value,row,index) {
                    if(value==''){
                        return Number(row.tVolumn).toFixed(fixedV);
                    }else{
                        return Number(value).toFixed(fixedV);
                    }
                }
            },{
                field:'orderStatus',
                title:'状态',
                formatter:function (value,row,index) {
                    return orderStatus[value];
                }
            },{
                field:'outroomDt',
                title:'出库时间'
            }
        ]],
        loadFilter:function(data){
            if(data.code!='200'){
                $alert(data.message);
                return data.data;
            }
            return data.data;
        },
        onLoadSuccess:function(data){
            $("#inroom_order_table").datagrid('clearSelections');
        }
    })
}